import pytest
from data.clients import create_client_json, get_all_clients_json, get_client_json
from data.models import Client
from errors import Missing
from sqlalchemy import func


@pytest.fixture
def client_json():
    return {
        "name": "Alexander",
        "surname": "Ivanov",
        "credit_card": "1234567812345678",
        "car_number": "A000AA198",
    }


def test_create_client_json(db, client_json):
    client = client_json
    result = create_client_json(**client)
    assert result["id"] is not None
    client["id"] = result["id"]
    assert result == client
    assert db.session.query(func.count(Client.id)).scalar() == 1


def test_get_client_json(client_json):
    client = get_client_json(client_id=1)
    assert client["id"] == 1
    assert client == {"id": client["id"], **client_json}


def test_get_client_json_with_wrong_id():
    with pytest.raises(Missing):
        get_client_json(client_id=123)


def test_get_all_clients_json(client_json):
    result = get_all_clients_json()
    assert len(result) == 1
    client = result[0]
    assert client["id"] is not None
    assert client == {"id": client["id"], **client_json}
